import time
import asyncore
import socket


class EchoClient(asyncore.dispatcher):
    """一个简单的Echo客户端"""
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))
        self._writable = True

    def handle_connect(self):
        super().handle_connect()
        print("handle_connect")

    def handle_close(self):
        super().handle_close()
        print("handle_close")

    def handle_read(self):
        result = self.recv(1024)
        if len(result) == 0:
            return
        print("handle_read")
        print("result is ", str(result))

    def handle_write(self):
        print("handle_write: " + str(self))
        self.send(b"Hello World!")
        self._writable = False
        print("handle_write_end")

    def writable(self):
        return self._writable


if __name__ == '__main__':
    for _ in range(3):
        client = EchoClient('localhost', 6666)
    start = time.time()
    asyncore.loop()
    end = time.time()
    print("used time is : " + str(end - start))
